import $modal from "@/common/utils/modal";
import {ElLoading} from "element-plus";
import router from "@/common/router";

export function parseByteSize(byteSize) {
    if (!byteSize) return '未知';

    if (byteSize * 1 > 1024 * 1024 * 1024) {
        return (byteSize * 1 / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
    }

    if (byteSize * 1 > 1024 * 1024) {
        return (byteSize * 1 / (1024 * 1024)).toFixed(2) + ' MB'
    }

    if (byteSize * 1 > 1024) {
        return (byteSize * 1 / (1024)).toFixed(2) + ' KB'
    }

    return byteSize * 1 + ' 字节';
}

export function trimStr(value) {
    if (!value) return "";
    return value.replace(/\s+/g, "")
}

export function urlFileSuffix(value) {
    const lastDotIndex = value.lastIndexOf('.');
    if (lastDotIndex !== -1) {
        return "." + value.substring(lastDotIndex + 1).toLowerCase();
    }
    return ""; // 没有找到文件后缀
}

export function routerPush(routePath, param = null) {
    let queryParam = {}
    if (param) {
        if (typeof param === 'string') queryParam = JSON.parse(param)
    }
    router.push({path: routePath, query: queryParam})
}

/**
 * 参数处理
 * @param {"id":10} params  参数
 * @param questionStr  问号前缀默认为空
 */
export function parseGetParam(params, questionStr = '') {
    let result = ''
    console.log()
    if (!params || typeof params === 'string' || Object.keys(params).length === 0) {
        return questionStr + result;
    }

    for (const propName of Object.keys(params)) {
        const value = params[propName];
        console.log(propName)
        console.log(value)
        let part = encodeURIComponent(propName) + "=";
        if (value !== null && value !== "" && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        let subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }

    return questionStr + result
}

/**
 * 参数处理
 * @param {"id":10} params  参数
 */
export function jsonToUrlParam(json) {
    if (json) {
        let obj = json;
        if (typeof json === 'string') obj = JSON.parse(json)
        return parseGetParam(obj)
    }
    return "";
}

/**
 * 复制内容到剪切板
 */
export function clipboard(value, msg = '复制成功', callback = () => {
}) {
    //浏览器禁用了非安全域的 navigator.clipboard 对象
    //在线上环境会报错 TypeError: Cannot read properties of undefined (reading 'writeText')
    if (!navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(value).then(() => {
            $modal.success(msg, 1000)
            callback();
        });
    } else {
        // 判断是否支持拷贝
        if (!document.execCommand('copy')) return Promise.reject()

        // 创建标签，并隐藏
        const textArea = document.createElement('textarea')
        textArea.style.position = 'fixed'
        textArea.style.top = textArea.style.left = '-100vh'
        textArea.style.opacity = '0'
        textArea.value = value
        document.body.appendChild(textArea)

        // 聚焦、复制
        textArea.focus()
        textArea.select()
        new Promise((resolve, reject) => {
            // 不知为何，必须写这个三目，不然copy不上
            document.execCommand('copy') ? resolve : reject
            textArea.remove()
            $modal.success(msg, 1000)
            callback();
        })
    }
}

export function blankStr(value, defaultValue = '') {
    if (value) return value;
    if (value == 'undefined') return defaultValue;
    return defaultValue;
}

export function subStr(value, size = 1000000) {
    if (value && value.length > size) return value.substring(0, size) + '...';
    return value;
}

export function parseTree(allList, idKey = 'id', pidKey = 'pid', childrenKey = 'children') {
    //根数组
    let genArray = gen(allList, idKey, pidKey);
    let genIds = genArray.map((e) => {
        return e[idKey]
    });

    //非根节点数组
    let childArray = [];
    for (let key in allList) {
        let id = allList[key][idKey] + ""
        //id不在根里，说明它是子路由
        if (genIds.indexOf(id) === -1) {
            childArray.push(allList[key])
        }
    }
    //非根节点数组
    let routerArray = [];
    for (let key in genArray) {
        routerArray.push(sort(genArray[key], childArray, idKey, pidKey, childrenKey));
    }
    return routerArray
}

export function copyNew(obj) {
    return JSON.parse(JSON.stringify(obj))
}

function gen(allList, idKey = 'id', pidKey = 'pid') {
    let ids = [];
    let gen = [];
    for (let key in allList) {
        ids.push(allList[key][idKey] + "")
    }
    for (let key in allList) {
        let pid = allList[key][pidKey] + ""
        //pid在id里面不存在，说明它是根
        if (ids.indexOf(pid) === -1) {
            gen.push(allList[key])
        }
    }
    return gen
}

function sort(parent_obj, allList, idKey = 'id', pidKey = 'pid', childrenKey = 'children') {
    let child_list = [];
    for (let i = 0; i < allList.length; i++) {
        let now_obj = allList[i];
        let now_pid = now_obj[pidKey];
        //查得到
        if (now_pid.toString() === (parent_obj[idKey] + "")) {
            child_list.push(now_obj); //同级别添加
            sort(now_obj, allList); //继续递归
        }
        //不同级别不做处理
        else {
        }
        if (child_list.length !== 0) {
            parent_obj[childrenKey] = child_list;
        }
    }
    return parent_obj
}

export let LOADING;

export function loading(text = '正在加载...') {
    LOADING = ElLoading.service({
        lock: true,
        text: text,
        background: 'rgba(0, 0, 0, 0.7)',
    });
}

export function closeLoading() {
    LOADING.close();
}
